//
//  UserAccount.swift
//  Tanenbaum_blog
//
//  Created by Tanenbaum on 15/7/30.
//  Copyright © 2015年 GZJ. All rights reserved.
//

import UIKit

//用户模型
class UserAccount: NSObject,NSCoding {
    
    class var userLogon: Bool {
        
        return shareAccount != nil
    }
   
    //用于调用access_token，接口获取授权后的access token。
    var access_token: String?
    
    //access_token的生命周期，单位是秒数
    var expires_in: NSTimeInterval = 0 {
     
        didSet{
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    var expiresDate: NSDate?
    //当前授权用户的UID。
    var uid: String?
    
    var name: String?
    
    var avatar_large: String?
    
    //MARK:--归档&解档
    //定义归档保存路径
    
    private static let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingPathComponent("account.plist")
    
    //保存账户信息
    func saveAccount() {
        NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.accountPath)
    }
    
    //MARK: --加载用户信息，调用方法，异步获取用户附加信息，保存当前信息
    
    func loadUserInfo(finished:(error:NSError?)->()) {
        NetWorkTools.sharedTools.loadUserInfo(uid!) { (result, error) -> () in
            
            if error != nil {
                finished(error: error)
                return
            }
            
            //设置用户信息
            self.name = result!["name"] as? String
            self.avatar_large = result!["avatar_large"] as? String
            
            //保存用户信息
            self.saveAccount()
            
            finished(error: nil)
        }
    }
    
    
     /**
       由于后续的每次网络请求都需要token，每次都需要读取
    
       如果每次都要“解档”，需要从磁盘读取，实际开发中，需要注意缓存
     */
    
    //设置静态类变量 静态加载账户信息
    private static var userAccount: UserAccount?
    

    //加载用户信息
    class var shareAccount : UserAccount? {
        
        //如果静态账户为空,则需要解档
        if userAccount == nil {
            
           userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount
        }
        
        /// 如果token过期，则把账户置空
        if let date = userAccount?.expiresDate where date.compare(NSDate()) == NSComparisonResult.OrderedAscending {
            
            userAccount == nil
        }
        
        return userAccount
    }
    
    
    //字典转模型
    init(dict:[String: AnyObject]) {
        
        super.init()
        
        setValuesForKeysWithDictionary(dict)
        
        //设置全局用户信息
        UserAccount.userAccount = self
    }
    
    //MARK --Nscoding
    //归档 --将自定义对象转换为二进制数据保存到磁盘
    func encodeWithCoder(aCoder: NSCoder) {
        
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeObject(uid, forKey: "uid")
        
    }
    
    //解档 --将二进制数据从磁盘恢复成自定义对象
    required init?(coder aDecoder: NSCoder) {
        
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        uid = aDecoder.decodeObjectForKey("uid") as? String
        
    }
    
    //重写setvalue方法，避免模型字典不匹配出错
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
  
    //重写description
    override  var description: String {
    
        let  properties = ["access_token","expires_in","uid","expiresDate","name","avatar_large"];
        
        return "\(dictionaryWithValuesForKeys(properties))"
     
    }
}
